package util.server;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class Uploader
{
	public Uploader(File f)
	{
		Socket s = null;
		try
		{
			s = new Socket(InetAddress.getByName("qaypn7.ec.resnet.columbia.edu"), Server.serverPort);
			Charset c = Charset.forName("UTF-8");
			ByteBuffer buff = c.encode(f.getName());
			DataOutputStream dos = new DataOutputStream(s.getOutputStream());
			byte[] data = buff.array();
			dos.writeInt(data.length);
			dos.write(data);
			FileInputStream fis = new FileInputStream(f);
			byte[] fileData = new byte[(int)f.getTotalSpace()];
			fis.read(fileData);
			dos.writeInt(fileData.length);
			dos.write(fileData);
		}
		catch(IOException e)
		{
			System.out.println("failed!");
			e.printStackTrace();
		}
		finally
		{
			if(s != null)
			{
				try
				{
					s.close();
				}
				catch(IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}
	public static void main(String[] args)
	{
		if(args.length > 0)
		{
			File f = new File(args[0]);
			if(f.exists())
			{
				System.out.print("uploading "+f.getAbsolutePath()+"... ");
				new Uploader(f);
				System.out.println("done!");
			}
		}
	}
}
